package gui.util;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import utils.Expert;

import actions.ExpertCreator;

/**
 * 
 * @author dernasherbrezon
 *
 */
public class EditExpertFrame extends JDialog
{
	private ExpertCreator creator;
	private Expert expertToEdit;
	
	private JComboBox role = new JComboBox();
	private JTextField expertName = new JTextField(20);
	public EditExpertFrame(ExpertCreator creator)
	{
		this(creator,null);
	}
	
	public EditExpertFrame(ExpertCreator creator,Expert expertToEdit)
	{
		setTitle("Добавление эксперта");
		this.creator = creator;
		this.expertToEdit = expertToEdit;
		
		role.addItem(Expert.LEADER_EXPERT);
		role.addItem(Expert.CALC_EXPERT);
		role.addItem(Expert.LOGIC_EXPERT);
		role.addItem(Expert.SECRETARY_EXPERT);
		
		if(expertToEdit!=null)
		{
			//TODO заголовок как звучит?
			setTitle("Редактирование профиля эксперта");
			expertName.setText(expertToEdit.name);
			role.setSelectedItem(expertToEdit.role);
		}
		
		getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
		getContentPane().add(expertName);
		getContentPane().add(role);
		getContentPane().add(createBottom());
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		setModal(true);
		setResizable(false);
		int resX = getGraphicsConfiguration().getBounds().width;
		int resY = getGraphicsConfiguration().getBounds().height;
		setBounds(resX/2 - getPreferredSize().width/2, resY/2 - getPreferredSize().height/2,0,0);
		pack();
		setVisible(true);		
	}
	
	private void checkInputValues() throws Exception
	{
		if(expertName.getText().length()==0)
		{
			throw new Exception("Не указано имя эксперта!");
		}
	}
	
	private JPanel createBottom()
	{
		JPanel retValue = new JPanel();
		retValue.add(new JButton(new AbstractAction("Ok")
		{
			public void actionPerformed(ActionEvent arg0)
			{
				try
				{
					checkInputValues();
				}
				catch(Exception e)
				{
					JOptionPane.showMessageDialog(null,e.getMessage(),"Ошибка!",JOptionPane.ERROR_MESSAGE);
					return;
				}
				if(expertToEdit==null)
				{
					Expert newExpert = new Expert(expertName.getText(),role.getSelectedItem().toString());
					creator.addExpert(newExpert);
				} else {
					expertToEdit.name = expertName.getText();
					expertToEdit.role = role.getSelectedItem().toString();
					creator.refresh();
				}
				EditExpertFrame.this.dispose();
			}
		}));
		retValue.add(new JButton(new AbstractAction("Отмена")
		{
			public void actionPerformed(ActionEvent arg0)
			{
				EditExpertFrame.this.dispose();
			}
		}));
		return retValue;
	}
}
